package com.lanou.bookstore.book.web.servlet;

import com.lanou.bookstore.book.domain.Book;
import com.lanou.bookstore.book.service.BookService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/book")
public class BookServlet extends HttpServlet {
    private BookService bookService = new BookService();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String cid = request.getParameter("cid");
        String bid = request.getParameter("bid");

        if (cid != null && bid == null) {
            if ("all".equals(cid)) {
                List<Book> bookList = bookService.findAll();
                request.setAttribute("bookList", bookList);
                request.getRequestDispatcher("/jsps/book/list.jsp").forward(request, response);
            } else {
                List<Book> bookList = bookService.findByCid(cid);
                request.setAttribute("bookList", bookList);
                request.getRequestDispatcher("/jsps/book/list.jsp").forward(request, response);
            }
        } else if (cid == null && bid != null) {
            Book book = bookService.load(bid);
            request.setAttribute("book", book);
            request.getRequestDispatcher("/jsps/book/desc.jsp").forward(request, response);
        }
    }
}
